package com.xhwl.centiotdata.suppliersystem.haikang;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.HaiKangInfoConstant;
import com.xhwl.centiotdata.pojo.dto.haikanginfo.DeviceHaiKangInfoDTO;
import com.xhwl.centiotdata.pojo.dto.haikanginfo.InfoIntegrationPropertiesDTO;
import com.xhwl.common.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author： wuyuhao
 * @Description：
 * @Date 2022/7/29
 */
@Service
public class DeviceHaiKangInfoHandler {

    private static final Logger log = LoggerFactory.getLogger(DeviceHaiKangInfoHandler.class);

    // 获取设备
    public List<DeviceHaiKangInfoDTO> pullDevice(InfoIntegrationPropertiesDTO propertiesDTO) {
        List<DeviceHaiKangInfoDTO> doorHaiKangDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<DeviceHaiKangInfoDTO> recordList = null;
        do {
            recordList = this.requestDevice(pageNum, propertiesDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            doorHaiKangDTOList.addAll(recordList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return doorHaiKangDTOList;
    }

    private List<DeviceHaiKangInfoDTO> requestDevice(Integer pageNum, InfoIntegrationPropertiesDTO propertiesDTO) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("pageNo", pageNum);
        params.put("pageSize",500 );
        JSONObject dataObject = this.post(HaiKangInfoConstant.DEVICE_INFO_URL,
                params,
                propertiesDTO.getAppKey(),
                propertiesDTO.getAppSecret(),
                propertiesDTO.getIpAndPort());
        JSONArray list = dataObject.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.toJavaList(DeviceHaiKangInfoDTO.class);
    }

    public JSONObject post(String url, Object params, String ak, String sk, String ipAndPort) {
        String path = ipAndPort + HaiKangInfoConstant.ARTEMIS + url;
        String result = null;
        String jsonParam = JSON.toJSONString(params);
        jsonParam = jsonParam.replace("\\r\\n", "");
        try {
            Map<String, String> header = new HashMap<>();
            header.put("Accept", "*/*");
            header.put("Content-Type", "application/json");
            header.put("x-ca-key", ak);
            header.put("x-ca-signature", geneSign(ak, sk));
            header.put("x-ca-signature-headers", "x-ca-key");
            log.info("header info:{}", header);

            result = HttpRequest
                    .post(path)
                    .addHeaders(header)
                    .body(jsonParam)
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【HaiKangInfo post exception】path:{};params:{}", path, jsonParam);
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【HaiKangInfo post result is null】path:{}", path + "  " + jsonParam);
        }
        JSONObject resultObject = JSON.parseObject(result);

        log.info("请求海康信息发布系统返回信息:{}", resultObject);
        if (!"0".equals(resultObject.getString("code"))) {
            log.error("【HaiKangInfo post failed】path:{};params:{};msg:{}", path, jsonParam, resultObject.getString("msg"));
        }
        Object data = resultObject.get("data");
        if (data instanceof JSONObject) {
            return resultObject.getJSONObject("data");
        } else {
            return resultObject;
        }
    }

    private String geneSign(String ak, String sk) {
        String sign = null;
        try {
            String stringToSign = "POST\n" +
                    "*/*\n" +
                    "application/json\n" +
                    "x-ca-key:" + ak + "\n" +
                    HaiKangInfoConstant.ARTEMIS + HaiKangInfoConstant.DEVICE_INFO_URL;
            log.info("签名字符串：{}",stringToSign);
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            byte[] keyBytes = sk.getBytes("UTF-8"); //secret 为 APP 的密钥。
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
            sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes("UTF-8"))));
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("签名：{}",sign);
        return sign;
    }
}
